<?php
/**
 * Created by PhpStorm.
 * User: win7
 * Date: 2018/4/7
 * Time: 16:38
 */

namespace App\Http\Controllers\Bap;

use App\Http\Controllers\Controller;
use App\Library\BTC\BitcoinFunction;
use App\Library\ETH\EthereumFunction;
use App\Library\OBA\ObaFunction;
use App\Models\Currency;
use App\Models\Order;
use App\Models\Property;
use App\Models\PropertyInfo;
use App\Models\Turn;
use App\Models\User;
use App\Models\Wallet;
use DB;
use Illuminate\Http\Request;
use League\Flysystem\Exception;
use App\Library\Orders\Orders;
use App\Library\Orders\Turns;

class PropertyController extends Controller
{
    /**
     * 用户USDT资产
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/4/7
     * @access public|private|protected
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function user_property(Request $request)
    {
        $info = $request->all();

        if (!empty($info['uid'])) {
            $uid = $info['uid'];
        } else {
            return respF(1003);
        }

        $map['is_standard'] = 1;
        $map['pay_switch']  = 1;
        $map['buy_switch']  = 1;

        $where['uid'] = $uid;
        $where['cid'] = Currency::where($map)->first(['id'])->id;

        $user_property = Property::where($where)->first()->toArray();

        return response()->json(['status' => 1, 'msg' => '查询成功', 'list' => $user_property]);
    }

    /**
     * 账户余额
     * @date 2018/04/9
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function property_list(Request $request)
    {
        $uid = $request->get('uid');
        $hide = $request->get('hide') ?? 0;

        if (empty($uid)) {
            return respF(1003);
        }
        $orders_model = new Orders();
        $ids = $orders_model->currency_id()->toArray();
        //判断是否隐藏0资产的
        if ($hide == 1) {
            $property = Property::whereIn('cid',$ids)->where('uid', $uid)->where('total','>',0)->paginate(10);
        } else {
            $property = Property::whereIn('cid',$ids)->where('uid', $uid)->paginate(10);
        }

        if (collect($property)->count() == 0) {
            return respF(1015);
        }

        $data = [];
        //总资产计算
        $total = 0;

        $data['count'] = $property->count();

        foreach ($property as $key => $value) {
            $data['list'][$key]['c_name']  = $value->currency ? $value->currency->name_en : '';
            $data['list'][$key]['cid']     = $value->currency ? $value->currency->id : 0;
            $data['list'][$key]['balance'] = $value->balance;
            $data['list'][$key]['blocked'] = $value->blocked;
            $data['list'][$key]['total']   = $value->total;
            //获取最新成交价
            $order = Order::where('cid', $value->cid)->orderBy('created_at', 'desc')->first();
            //没有获取官方初定价
            if (collect($order)->count() == 0) {
                $price = Currency::where('id', $value->cid)->value('official_price');
            } else {
                $price = $order->price;
            }
            //dump($price);
            //如果是USDT则直接加
            if ($value->total > 0) {
                if ($value->currency->name_en == 'USDT') {
                    $total = bcadd($total, $value->total, 2);
                } else {
                    $total = bcadd($total, bcmul($value->total, $price, 2), 2);
                }
            }
        }

        $data['usdt_price'] = $total;

        $cny = UsdRate() ?? 6.3;

        $data['cny_price'] = bcmul($total, $cny, 2);

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 账单
     * @date 2018/04/9
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function bill_list(Request $request)
    {
        $info = $request->all();
        $data = [];
        if (empty($info['uid'])) {
            return respF(1003);
        }
        if (!empty($info['cid'])) {
            $where['cid'] = $info['cid'];
        }
        $where['uid']  = $info['uid'];
        $list          = PropertyInfo::where($where)->orderBy('id', 'desc')->paginate(10);
        $data['count'] = PropertyInfo::where($where)->orderBy('id', 'desc')->count();

        //处理数据
        if (collect($list)->count() == 0) {
            return respF(1015);
        }
        foreach ($list as $key => $val) {
            $data['list'][$key]['c_name'] = $val->currency->name_en;
            $data['list'][$key]['note']   = $val->note;
            $data['list'][$key]['total']  = $val->total;
            if ($val->type == 3 || $val->type == 4) {
                if ($val->deal_type == 2 || $val->deal_type == 3) {
                    $data['list'][$key]['status'] = '支出';
                } else {
                    $data['list'][$key]['status'] = '收入';
                }
            } elseif ($val->type == 1) {
                $data['list'][$key]['status'] = '支出';
            } elseif ($val->type == 2) {
                $data['list'][$key]['status'] = '收入';
            }
            $data['list'][$key]['type']       = $val->type;
            $data['list'][$key]['deal_type']  = $val->deal_type;
            $data['list'][$key]['type']       = $val->type;
            $data['list'][$key]['deal_type']  = $val->deal_type;
            $data['list'][$key]['created_at'] = $val->created_at->format('Y-m-d H:i:s');
        }

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }
    /**
     * 账单
     * @date 2018/04/9
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function finance_list(Request $request)
    {
        $info = $request->all();
        if (empty($info['uid'])) {
            return respF(1003);
        }
        if (!empty($info['cid'])) {
            $where['cid'] = $info['cid'];
        }
        $where['uid'] = $info['uid'];

        $data = [];
        $list = PropertyInfo::where($where)->where('type', 1)
            ->orWhere('type', 2)->orderBy('created_at', 'desc')->paginate(10);
        $data['count'] = PropertyInfo::where($where)->where('type', 1)
            ->orWhere('type', 2)->orderBy('created_at', 'desc')->count();

        if (collect($list)->count() == 0) {
            return respF(1015);
        }
        foreach ($list as $k => $value) {
            $data['list'][$k]['c_name']     = $value->currency->name_en;
            $data['list'][$k]['num']        = $value->num;
            $data['list'][$k]['c_num']      = $value->num;
            $data['list'][$k]['created_at'] = $value->created_at->format('Y-m-d H:i:s');
            if ($value->type == 1) {
                $data['list'][$k]['type'] = '充币';
            } else {
                $data['list'][$k]['type'] = '提币';
            }

        }

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }
    /**
     * 提币提交接口
     * @date 2018/04/13
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function turn_out_submit(Request $request)
    {
        $info = $request->all();
        //验证参数
        if (empty($info['address']) || empty($info['cid']) || empty($info['uid'])
            || empty($info['psd']) || empty($info['num'])) {
            return respF(1003);
        }
        //查找用户
        $user = User::find($info['uid']);
        //用户不存在
        if (collect($user)->count() == 0) {
            //返回错误提示
            return respF(1001);
        }
        //验证交易密码
        if (md5($info['psd']) != $user->pay_pass) {
            //交易密码错误
            return respF(2000);
        }
        //验证用户资产
        $property_u = Property::where(['uid' => $info['uid'], 'cid' => $info['cid']])->first();
        //没有资产
        if (collect($property_u)->count() == 0) {
            //账号资产不足
            return respF(1036);
        }
        //验证资产
        if ((float) $info['num'] > (float) $property_u->balance) {
            //账号资产不足
            return respF(1036);
        }
        //币种
        $currency = Currency::find($info['cid']);
        //验证币种
        if (collect($currency)->count() == 0) {
            //货币信息错误
            return respF(2001);
        }
        //币种名称
        $c_name = $currency->name_en;
        //实例化币种操作类
        switch ($c_name) {
            case 'BTC':
            case 'LTC':
            case 'DGC':
                $function = new BitcoinFunction($c_name);
                break;
            case 'ETH':
                $function = new EthereumFunction();
                break;
            case 'OBA':
                $function = new ObaFunction();
                break;
            default:
                return respF(2031);
        }
        //验证地址
        $re_m = $function->addressValidator($info['address']);
        //验证地址失败
        if (!$re_m) {
            return respF(1032);
        }
        //判断是否系统钱包
        $add_now = Wallet::where('address', $info['address'])->first();
        //如果是系统钱包
        if ($add_now) {
            //转出钱包是系统钱包
            return respF(1033);
        }
        //计算手续费
        $data1['uid']            = $info['uid'];
        $data1['cid']            = $info['cid'];
        $data1['wallet_address'] = $info['address'];
        $data1['num']            = (float) $info['num'];
        $data1['proc']           = (float) $currency->out_fee * $data1['num'] / 100;
        $data1['real_num']       = $data1['num'] - $data1['proc'];
        $data1['type']           = 2;
        $data1['status']         = 1;
        $data1['trade_time']     = time() + 60 * 60 * 2;
        $data1['unlock_time']    = $data1['trade_time'] + 60 * 60 * 6;

        Turn::create($data1);
        $property_u->decrement('balance', (float) $info['num']);
        $property_u->increment('blocked', (float) $info['num']);

        return response()->json(['status' => 1, 'msg' => '提交成功']);
    }
    /**
     * 提币显示接口
     * @date 2018/04/13
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function turn_info(Request $request)
    {
        $info = $request->all();

        if (empty($info['id']) || empty($info['cid'])) {
            return respF(1003);
        }

        $result = Property::where(['uid' => $info['id'], 'cid' => $info['cid']])
            ->select('uid', 'cid', 'balance', 'blocked')->first();

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $result]);

    }
    /**
     * 充币
     * @date 2018/04/15
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function currency_swap(Request $request)
    {
        $info = $request->all();
        //验证参数
        if (empty($info['cid']) || empty($info['uid'])) {
            return respF(1003);
        }

        $uid      = $info['uid'];
        $cid      = $info['cid'];
        $currency = Currency::where('id', $cid)->first();
        //判断币种是否存在
        if (!$currency) {
            return respF(2001);
        }
        $c_name = $currency->name_en;
        //验证是否支持充币的币种
        if (!in_array($c_name, ['BTC', 'LTC', 'DGC', 'ETH', 'OBA'])) {
            return respF(2031);
        }
        //查询资产
        $property = Property::where(['uid' => $uid, 'cid' => $cid])->first();
        //返回参数拼接
        $list            = array();
        $list['cid']     = $cid;
        $list['uid']     = $uid;
        $list['into_fee']  = $currency->into_fee;
        $list['into_value']  = $currency->into_value;
        $list['c_name']  = $currency->name_en;
        $list['balance'] = $property->balance ?? 0;
        $list['blocked'] = $property->blocked ?? 0;
        //查询记录条件
        $map['cid']    = $cid;
        $map['uid']    = $uid;
        $map['status'] = 1;
        $map['type']   = 1;
        //是否已有充币且未过期的记录
        $wallet = Turn::where($map)->where('trade_time', '>', time())->first();
        //有记录，直接返回
        if ($wallet) {
            $list['address'] = $wallet->wallet_address;

        }else{
            $tuans_model = new Turns();
            $tuans = $tuans_model->into($uid,$cid,$c_name);
            if (!$tuans||$tuans==false){
                return respF(1018);
            }else{
                $list['address'] = $tuans;
            }
        }
        return response()->json(['status' => 1, 'msg' => '成功', 'data' => $list]);
    }
    /**
     * 全部币种
     * @date 2018/04/20
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function current_list(Request $request)
    {
        $where['online_switch'] = 1;
        $where['pay_switch'] = 1;
        $where['buy_switch'] = 1;
        $result = Currency::where($where)->select('name_en')->get();

        foreach ($result as $k => $value) {
            $list[$k]['text']  = $value['name_en'];
            $list[$k]['value'] = $value['name_en'];
        }

        return response()->json(['status' => 1, 'msg' => '成功', 'data' => $list]);
    }


    /**
     * 用户资产信息
     *
     * @ author: ZUORENCI
     * @ E-mail:904725327@qq.com
     * @ date: 2018/6/21
     * @access public|private|protected
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function user_property_list(Request $request){
        $uid = $request->get('uid');
        if (empty($uid))
            return respF(1003);
        $where['pay_switch'] = 1;
        $where['buy_switch'] = 1;
        $where1['uid'] = $uid;
        $list = Currency::where($where)->get(['id', 'name_en', 'logo']);
        if (!$list)
            return respF(1004);
        $list = $list->toArray();
        foreach ($list as $k => $v) {
            if($v['name_en']=='USDT'){
                unset($list[$k]);
            }else{
                $where1['cid'] = $v['id'];
                $list[$k]['is_ok'] = 0;
                if (Property::where($where1)->first())
                    $list[$k]['is_ok'] = 1;
                $list[$k]['logo'] = config('alioss.host').'/'. $v['logo'];
            }
        }
        $data['type'] = 0;
        if (count($list) > 0) {
            $data['type'] = 1;
            $data['list'] = array_values($list);
        }
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);

    }
    
    
    
    
}
